import lxml

# html = """
# <!DOCTYPE html>
# <html lang="en">
# <head>
#     <meta charset="UTF-8">
#     <title class="center" style="height: 50px; color: red;">this is a html page</title>
# </head>
# <body>
#     <form>
#         <table>
#             <tbody>
#                 <tr class="info"><td>zhangshan</td><td>45</td></tr>
#                 <tr class="info"><td>lisi</td><td>23</td></tr>
#                 <tr class="info"><td>bob</td><td>12</td></tr>
#             </tbody>
#         </table>
#         <span>
#             line1
#             line2
#             line3
#             line4
#             line5
#         </span>
#     </form>
# </body>
# </html>
# """
from lxml.etree import HTML

with open("./example.html", "r", encoding="utf-8") as fp:
    content = fp.read()
    html = HTML(content)
    assert isinstance(html, lxml.etree._Element)
    # 完整路径查找
    # nodes = html.xpath("/html/body/form/table/tbody/tr")
    # 方法二
    #nodes = html.xpath("//tr")
    # 方法三，通过元素的属性查找
    # nodes = html.xpath("//tr[@class='info']")
    #
    # print(nodes)
    #
    # for node in nodes:
    #     # print(type(node))
    #     assert isinstance(node, lxml.etree._Element)
    #     # print(node.tag)
    #     # print(node.text)
    #     # print(node.attrib)
    #     # 相对路径查找
    #     user = node.xpath("./td")
    #     username = user[0]
    #     age = user[1]
    #     print(username.text, age.text)


    # 通过索引查找
    # lisi = html.xpath("//table[1]/tbody/tr[2]")
    # for l in lisi:
    #     user = l.xpath("./td[1]")[0]
    #     age = l.xpath("./td[2]")[0]
    #     print(user.text, age.text)


    # XPATH的内置函数
    # lisi = html.xpath('//table[1]/tbody/tr[last()]')
    # assert isinstance(lisi, lxml.etree._Element)
    # for l in lisi:
    #     user = l.xpath("./td[1]")[0]
    #     age = l.xpath("./td[2]")[0]
    #     print(user.text, age.text)

    # lisi = html.xpath('//table[1]/tbody/tr[last()]')
    # for l in lisi:
    #     assert isinstance(l, lxml.etree._Element)
    #     # node = l.find("./td")
    #     for e in l.findall("./td"):
    #         print(e.text)

        # print(l.findall("./td")) # == l.xpath("./td")
        # print(node.tag, node.text)


    # 遍历子元素
    # tbody = html.xpath("//table[1]/tbody")[0]
    # assert isinstance(tbody, lxml.etree._Element)
    # 访问儿子元素
    # for e in list(tbody):
    #     print(e.tag)

    # 遍历所有的子孙元素
    # for e in tbody.iter('td'):
    #     print(e.tag)


